define(['jquery', 'bootstrap', 'frontend', 'form', 'template','table','backend','backend/maputils'], 
function ($, undefined, Frontend, Form, Template,Table,Backend,map) {
    var arr=['在售','停售','已售','无效'];
    var labels=['success','primary','info','default'];

    var Controller = {
        seconditemslist:function(){

            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: '/api/second/items/lists' + location.search,
                    view_url: 'second/items/view',
                    table: 'second_items',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id', pageSize: 20,
                sortName: 'update_time',
                sortOrder: "desc",  showToggle:false,showExport:false,
                dblClickToEdit:false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),formatter:function(value,row,index){
                            var str=value;
                            if(row.view_level>0){
                                str += " <span class='label label-warning'>私</span>";
                            }else{
                                str += " <span class='label label-default'>公</span>";
                            }
                            return str;
                        }},
                        {field: 'newhousebuilding.areaName', title:'区域',operate: 'LIKE',formatter:function(c,r){
                            if(c){
                                var _array = c.split('/');
                                return _array[_array.length-1];
                            }else{
                                return "&nbsp;";
                            }
                        }},
                        {field: 'newhousebuilding.building_name', title:'小区名称',operate: 'LIKE'},
                        {field: 'dong', title: '栋',operate: 'LIKE'},
                        {field: 'shi_count', title:'房型',formatter:function(c,r){
                            return c + '室' + r.ting_count + '厅';
                        }},
                        {field: 'floor', title: '楼层',formatter:function(c,r){
                            return c + '/' + r.floor_total;
                        }},
                        {field: 'area', title: '面积', operate:'BETWEEN',formatter:function(c,r){
                            return c + ' m<sup>2</sup>';
                        }},
                        {field: 'unit_price', title:'元/平方', operate:'BETWEEN'},
                        {field: 'total_price', title: '总价', operate:'BETWEEN',formatter:function(c,r){
                            return c + '万';
                        }},
                        {field: 'customer_name', title:'房主',operate: 'LIKE'},
                        {field: 'seconddecoration.decoration', title:'装修'},
                        {field: 'newhousebuildingtypes.type_name', title:'类型'},
                        {field: 'state', title:'状态',formatter:function(value,row,index){
                            return "<span class='label label-" + labels[value] + "'>" + arr[value] + "</span>";
                        }},
                        {field: 'update_time', title: '更新时间', operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                        buttons:[
                            {
                                name:'view',
                                text:'查看',
                                title:'查看',
                                icon:'fa fa-building',
                                classname:'btn btn-xs btn-success btn-view btn-dialog',
                                url:'second/seconditemview'
                            }
                        ],formatter: Table.api.formatter.operate
                    }
                    ]
                ],
                responseHandler:function(res){
                    return {
                        "total":res.data.total,
                        "rows":res.data.rows
                    };
                }
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            table.on('post-body.bs.table',function(){
                $("a.btn-view").data('area',["60%","600px"]);
            });
            table.on('dbl-click-row.bs.table', function (e, row, element, field) {
                $(".btn-view", element).trigger("click");
            });
        },
        /// 收藏房源列表 
        secondfavoratelist:function(){
              // 初始化表格参数配置
              Table.api.init({
                extend: {
                    index_url: '/api/second/favorates/lists' + location.search,
                    view_url: 'second/items/view',
                    table: 'second_items',
                    del_url: '/api/second/favorates/delfavorate',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'target_id', pageSize: 20,
                sortName: 'update_time',
                sortOrder: "desc",  showToggle:false,showExport:false,
                dblClickToEdit:false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'target_id', title: '房源编号'},
                        {field: 'seconditem.address', title:'地址',operate: 'LIKE',formatter:function(c,r){
                            if(c){
                                var _array = c.split('/');
                                return _array[_array.length-1];
                            }else{
                                return "&nbsp;";
                            }
                        }},
                        // {field: 'newhousebuilding.building_name', title:'小区名称',operate: 'LIKE'},
                        {field: 'seconditem.dong', title: '栋',operate: 'LIKE'},
                        {field: 'seconditem.shi_count', title:'房型',formatter:function(c,r){
                            return c + '室' + r.seconditem.ting_count + '厅';
                        }},
                        {field: 'seconditem.floor', title: '楼层',formatter:function(c,r){
                            return c + '/' + r.seconditem.floor_total;
                        }},
                        {field: 'seconditem.area', title: '面积', operate:'BETWEEN',formatter:function(c,r){
                            return c + ' m<sup>2</sup>';
                        }},
                        {field: 'seconditem.unit_price', title:'元/平方', operate:'BETWEEN'},
                        {field: 'seconditem.total_price', title: '总价', operate:'BETWEEN',formatter:function(c,r){
                            return c + '万';
                        }},
                        {field: 'seconditem.customer_name', title:'房主',operate: 'LIKE'},
                        // {field: 'seconddecoration.decoration', title:'装修'},
                        // {field: 'newhousebuildingtypes.type_name', title:'类型'},
                        {field: 'seconditem.state', title:'状态',formatter:function(value,row,index){
                            return "<span class='label label-" + labels[value] + "'>" + arr[value] + "</span>";
                        }},
                        {field: 'seconditem.update_time', title: '更新时间', operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                        buttons:[
                            {
                                name:'view',
                                text:'查看',
                                title:'查看',
                                icon:'fa fa-building',
                                classname:'btn btn-xs btn-success btn-view btn-dialog',
                                url:'second/seconditemview'
                            }
                        ],formatter: Table.api.formatter.operate
                    }
                    ]
                ],
                responseHandler:function(res){
                    return {
                        "total":res.data.total,
                        "rows":res.data.rows
                    };
                }
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            table.on('post-body.bs.table',function(){
                $("a.btn-view").data('area',["60%","600px"]);
            });
            table.on('dbl-click-row.bs.table', function (e, row, element, field) {
                $(".btn-view", element).trigger("click");
            });
        },
        seconditemview:function(){
            var html="<span class='label label-" + labels[state] + "'>" + arr[state] + "</span>";
            $("#tdState").html(html);
            //TODO: 地址
            if(lat && lng){
                map.init("map-container",lng,lat,function(e){
                    map.getLocation({lat:lat,lng:lng},function(result){
                        if(result){
                            $("#c-address").text(result.address); 
                        }
                    });
                });
            }else{
                map.init("map-container",117.17,31.52,function(e){
                    map.geo(building,function(point,ret){
                            
                    });
                });
               
            }
            renderFollow();
         
            function renderFollow(){
                console.info('加载跟进');
                // 加载跟进
                $.post('/api/second/follow/lists?sort=create_time&order=desc',{item_id:item_id}, function(data, ret){
                    //成功的回调
                    var value=data.data.rows;
                    $("#ulFollow").empty();
                    var state;
                    for(var i=0;i<value.length;i++){
                        var tmp=value[i];
                        if(i==0)state=tmp.state;
                        var str='<li>[' + tmp.create_time + ']';
                        str +='[ '+arr[ tmp.state] + ' ]';
                        str += tmp.comment;
                        // str += ' [ ' + tmp.admin.nickname + ' ] ';
                        str+='</li>';
                        $("#ulFollow").append(str);
                    }
                    if(state){
                        var html="<span class='label label-" + labels[state] + "'>" + arr[state] + "</span>";
                        $("#tdState").html(html);
                    }
                    return false;
                 });
            }
            /**
             * 新增跟进
             */
            $("#btnNewFollow").click(function(){
                Fast.api.open("/index/second_follow/add?item_id=" + item_id + '&state=' + state, '新增跟进', {
                    callback: function (data) {
                        console.log('render follow callback');
                        renderFollow();
                    }
                });
                return false;
            });
            /**
             * 收藏房源
             */
            $("#btnFavorate").click(function(){
                var me=$(this);

                if(me.hasClass('fa-star')){
                    $.post('/api/second/favorates/delfavorate',{ids:item_id},function(ret){
                        if(ret.code){
                            me.removeClass('fa-star').addClass('fa-star-o');
                            Toastr.success(ret.msg);
                        }else{
                            Toastr.error(ret.msg);
                        }
                    });
                }else{
                    $.post('/api/second/favorates/addfavorate',{ids:item_id},function(ret){
                        if(ret.code){
                            me.removeClass('fa-star-o').addClass('fa-star');
                            Toastr.success(ret.msg);
                        }else{
                            Toastr.error(ret.msg);
                        }
                    });
                }

            });
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});